import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button,Card,Form,Input,message,Switch} from 'antd';
import { ArrowLeftOutlined, } from '@ant-design/icons';
import { reqAddNotice,reqUpdateNotice } from '../../../api'
import { saveNoticeAction } from '../../../redux/action_creators/push_action';
import PicturesWall from '../../../components/util/picture_wall';
import RichTextEditor from '../../../components/util/rich_text_edit';
import './addUpdate.less';

const {Item} =Form;


@connect(
    (state)=>({
        noticeList:state.push.noticeList
    }),
    {
        saveNoticeList:saveNoticeAction
    }
)
class AddUpdate extends Component {
    state={
        operateType:'add',
        title:'',
        useStatus:1,
        img:'',
        detail:'',
        id:''
    }
    componentDidMount(){

        const { id } = this.props.match.params
        const { noticeList} = this.props
        if(id) {
            this.setState({operateType:'update'})
            if(noticeList.length){
               let result = noticeList.find((item)=>{
                   return item.id === parseInt(id)
               })
               if(result){
                   this.setState({...result})
                   if(result.img) this.pictureWall.setFileList(result.img.split(','))
                   this.textEditor.setDetail(result.detail)
               } 
            }else{
                const {img,detail,useStatus} = this.props.location.state.noticeItem
               if(img) this.pictureWall.setFileList(img.split(','))
                this.textEditor.setDetail(detail)
                this.setState({useStatus})
            }
        }else this.setState({operateType:'add'})
    }
    // 提交表单
    onFinish = async (values) => {
        // 从上传图片组件中获取图片地址数组
       let img = this.pictureWall.getImgArr()
       let detail = this.textEditor.getDetail()
       const title = values.title
       const useStatus = this.state.useStatus
       if(detail.length<9){
            message.error("请输入详细内容再提交！",1)
            return;
        }
        if(img.length<1){
            message.error("请上传封面图片再提交",1)
            return;
        }
        const noticeObj = {title,detail,img,useStatus}
        console.log(noticeObj);
       let result
       if(this.state.operateType === 'add'){
            result = await reqAddNotice({...noticeObj,img})
            const { code,data,msg } = result;
            if(code===200){
                message.success('添加成功！',1)
                let noticeList = [...this.props.noticeList]
                noticeList.unshift(data)
                this.props.saveNoticeList(noticeList)
                this.props.history.replace('/training/admin/push/notice')
            }else{
                message.error(msg,2)
            }
        }else{
            const id= this.props.location.state.noticeItem.id
             result = await reqUpdateNotice({...noticeObj,img,id})
             const { code,data,msg } = result;
             console.log(data);
             if(code===200){
                 message.success('修改成功',1)
                 let noticeList = [...this.props.noticeList]
                 noticeList = noticeList.map((item)=>parseInt(item.id) ===parseInt( data.id) ? data : item);
                 console.log(noticeList);
                 this.props.saveNoticeList(noticeList)
                 this.props.history.replace('/training/admin/push/notice')
             }else{
                 message.error(msg,1)
             }
        }

    };
    // 表单填写有误
    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
        // message.error('表单有误，请检查！',1)
    };
    onChangeUseStatus=()=>{
        const useStatus = this.state.useStatus
        if(useStatus===1) this.setState({useStatus:0})
        else this.setState({useStatus:1})
    }
    render() {
        const { operateType } = this.state
        const {title,detail,useStatus} = this.props.location.state.noticeItem
        return (
            
                <Card 
                    title={
                        <div className="left-top">
                            <Button 
                                type="link" 
                                size="small"
                                onClick={()=>{this.props.history.goBack()}} 
                            >
                                <ArrowLeftOutlined/>
                            </Button>
                            <span>{operateType==='update'?'公告修改':'公告添加'}</span>
                        </div>
                    }          
                >
                <Form
                    labelCol= {{span: 2,}}
                    wrapperCol= {{span: 6}}
                    name="basic"
                    initialValues={{
                        remember: true,
                        
                    }}
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                >
                    <Item label="标题"
                        name="title"
                            initialValue={title || ''}
                        rules={[{required: true,message: '标题不能为空',}]}
                    >
    
                        <Input placeholder="请输入标题"  allowClear/>
                    </Item>
                    <Item label="封面图片"
                            name="img"
                            wrapperCol= {{span: 12}} >
                            <PicturesWall ref={(pictureWall)=>{this.pictureWall = pictureWall}}/>
                        </Item>  
                    <Item label="公告详情"
                        name="detail"
                        initialValue={detail || ''}
                        wrapperCol= {{span: 14  }}
                    >      
                    <RichTextEditor ref={(textEditor)=>{this.textEditor = textEditor}}/>
                    </Item>
                   { operateType==='update'?'':
                    <Item label="是否启用"
                        name="useStatus"
                        valuePropName="checked"
                    >
                        <Switch checkedChildren="已启用" unCheckedChildren="未启用" onClick={this.onChangeUseStatus} defaultChecked={parseInt(useStatus)===0?false:true}/>                   
                    </Item>}
                    <Item  wrapperCol={{ offset: 2, span: 24}} >
                        <Button  type="primary" htmlType="submit" className="login-from-button">提交</Button>
                    </Item>
                </Form>
                </Card>
            
        )
    }
}
export default  AddUpdate;